<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElForm, ElMessage, ElMessageBox, type FormRules, type UploadProps, type UploadUserFile, type FormInstance } from 'element-plus'
import { getDishesList } from '@/api/dishes'
import { getIngredientListByType } from '@/api/ingredients'
import type { Dishes, DishesSearchForm } from '@/api/dishes/types'
import type { Ingredients } from '@/api/ingredients/types'
import { useTokenStore } from '@/stores/tokenStore'
import type { Cart } from '@/api/cart/types'
import { deleteFormCart, getCartList, saveOrUpdate } from '@/api/cart'
import { createOrder } from '@/api/order'
import type { OrderItem, OrderParam } from '@/api/order/types'

const tokenStore = useTokenStore()

const base_url = import.meta.env.VITE_APP_BASE_API

const pageNum = ref(1)
const pageSize = ref(4)
const total = ref(0)
const dishesList = ref<Dishes[]>([])

const queryFormRef = ref<FormInstance>()
const queryForm = reactive<DishesSearchForm>({
    main: '',
    minor: '',
    seasoning: ''
})

const mainList = ref<Ingredients[]>([])
const minorList = ref<Ingredients[]>([])
const seasonList = ref<Ingredients[]>([])
/** 购物车 */
const cartList = ref<Cart[]>([])
// 预制时间
const prepareTime = ref('')
// 保存选中表格中的数据
const prepareList = ref<Cart[]>([])


const listIngredient = async () => {
    mainList.value = await getIngredientListByType('1')
    minorList.value = await getIngredientListByType('2')
    seasonList.value = await getIngredientListByType('3')
}

const listDishes = async (pager = 1) => {
    pageNum.value = pager
    getDishesList(pageNum.value, pageSize.value, queryForm).then(res => {
        dishesList.value = res.rows
        total.value = res.total
    }).catch(err => {
        console.log(err)
    })
}

const resetForm = () => {
    queryFormRef.value?.resetFields()
}

watch(queryForm, (v1, v2) => {
    listDishes()
})

/** 获取购物车数据 */
const listCart = () => {
    getCartList().then(res => {
        cartList.value = res
    }).catch(err => {
        console.log(err)
    })
}

const changeCount = async (cart: Cart) => {
    await saveOrUpdate(cart)
    ElMessage.success('修改成功')
}

const addToCart = async (dishes: Dishes) => {
    let cart = cartList.value.find(item => item.dishId === dishes.id)
    if (cart) {
        ++cart.count
    } else {
        cart = { dishId: dishes.id, dishName: dishes.name, count: 1 }
    }
    await saveOrUpdate(cart)
    ElMessage.success('加入购物车成功')
    setTimeout(() => {
        listCart()
    }, 1000)
}

const deleteCart = async (id: number) => {
    await deleteFormCart([id])
    ElMessage.success('删除成功')
    cartList.value = cartList.value.filter(item => item.dishId !== id)
}

const cartChange = (val: Cart[]) => {
    prepareList.value = val

}

const disabledDate = (time: Date) => {
    return time <= new Date()
}

const confirm = async () => {
    let itemList: OrderItem[] = prepareList.value.map(item => {
        return {
            dishesId: item.dishId,
            dishesNum: item.count
        } as OrderItem
    })
    let orderParam: OrderParam = {
        prepareTime: prepareTime.value,
        itemList: itemList
    }
    await createOrder(orderParam)

    let ids: number[] = prepareList.value.map(item => item.dishId as number)

    await deleteFormCart(ids)

    listCart()
    //cartList.value = cartList.value.filter(cart => ids.includes(cart.dishId as number))
}




onMounted(() => {
    listIngredient()
    listDishes()
    listCart()
})


</script>

<template>
    <div class="app-container">
        <el-table :data="cartList" border stripe style="width: 100%;" @selection-change="cartChange">
            <el-table-column type="selection" width="55px" align="center"></el-table-column>
            <el-table-column label="菜品ID" prop="dishId" align="center"></el-table-column>
            <el-table-column label="菜品名" prop="dishName" align="center"></el-table-column>
            <el-table-column label="数量" prop="count" align="center">
                <template #default="scope">
                    <el-input-number v-model="scope.row.count" :min="1" :max="10" :step="1"
                        @change="changeCount(scope.row)" />
                </template>
            </el-table-column>
            <el-table-column label="删除" prop="action" align="center">
                <template #default="scope">
                    <el-button type="danger" icon="Delete" circle @click="deleteCart(scope.row.dishId)"></el-button>
                </template>
            </el-table-column>

        </el-table>
        <div style="display: flex;justify-content: flex-end;align-items: center; margin: 10px 0px;">
            <el-date-picker v-model="prepareTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择预制时间"
                :disabled="!disabledDate" />
            <el-divider direction="vertical" />
            <el-button type="primary" icon="Plus" plain :disabled="!disabledDate || prepareList.length == 0"
                @click="confirm">预制订单</el-button>
        </div>
        <el-form :model="queryForm" ref="queryFormRef" label-width="100px" inline>
            <el-form-item label="主料" prop="main">
                <el-select v-model="queryForm.main" clearable style="width: 180px;" placeholder="请选择主料">
                    <el-option v-for="item in mainList" :key="item.id" :value="item.id" :label="item.name"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="辅料" prop="minor">
                <el-select v-model="queryForm.minor" clearable style="width: 180px;" placeholder="请选择辅料">
                    <el-option v-for="item in minorList" :key="item.id" :value="item.id" :label="item.name"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="调料" prop="seasoning">
                <el-select v-model="queryForm.seasoning" clearable style="width: 180px;" placeholder="请选择调料">
                    <el-option v-for="item in seasonList" :key="item.id" :value="item.id"
                        :label="item.name"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="info" icon="Refresh" @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="20">
            <el-col :span="6" v-for="item in dishesList" :key="item.id">
                <el-card :body-style="{ padding: '0px' }" shadow="hover" style="margin-bottom: 20px;">
                    <img :src="base_url + item.url" style="width: 100%;display: block;height: 300px;" />
                    <div style="padding: 14px;">
                        <div class="dishes">
                            <span>{{ item.name }}</span>
                            <el-button link size="small" type="primary" @click="addToCart(item)">加入购物车</el-button>
                        </div>
                        <div class="ingredients">
                            <span>{{ '主要食材：' + item.mainName }}</span>
                        </div>
                        <div class="ingredients">
                            <span>{{ '辅助食材：' + item.minorName }}</span>
                        </div>
                        <div class="ingredients">
                            <span>{{ '调料：' + item.seasoningName }}</span>
                        </div>

                    </div>
                </el-card>
            </el-col>
        </el-row>
        <el-pagination style="margin-top: 20px;" :total="total" layout="total, prev, pager, next, jumper,sizes"
            :page-sizes="[4, 8, 12]" v-model:current-page="pageNum" v-model:page-size="pageSize"
            @current-change="listDishes" @size-change="listDishes()" size="small" />

    </div>
</template>

<style scoped>
.dishes {
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #1B1B1B;
    line-height: 1.4;
    height: 20px;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 14px;
    font-weight: bold;
    white-space: nowrap;
}

.ingredients {
    margin-top: 5px;
    font-size: 12px;
    color: #999;
}
</style>